import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
import store from '@/store';

const baseUrl = process.env.VUE_APP_API_BASE_URL || (
  process.env.NODE_ENV === 'production'
    ? 'http://localhost:8080'
    : '/admin3'  // 使用代理路径
);

const service: AxiosInstance = axios.create({
    baseURL: baseUrl,
    timeout: 300000
});

service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        if (config.headers) {
            // 修改为直接访问state或确保getter存在
            const user = store.state.SmartNeroUser || store.getters.getSmartNeroUser;   
            if (user?.token) {
                config.headers['Authorization'] = `Bearer ${user.token}`;
            }
        }
        return config;
    },
    (error) => {
        console.error('Request error:', error);
        return Promise.reject(error);
    }
);

// 封装 GET 请求
const get = (url: string, params = {}) => {
    return service.get(url, { params });
};

// 封装 POST 请求
const post = (url: string, data = {}) => {
    return service.post(url, data);
};

// 封装 PUT 请求
const put = (url: string, data = {}) => {
    return service.put(url, data);
};

// 封装 DELETE 请求
const del = (url: string, params = {}) => {
    return service.delete(url, { params });
};

// 新增流式请求方法
const stream = (url: string, params = {}) => {
  const queryString = new URLSearchParams(params).toString();
  return fetch(`${baseUrl}${url}?${queryString}`, {
    headers: {
      'Authorization': `Bearer ${(store.state.SmartNeroUser || store.getters.getSmartNeroUser)?.token || ''}`
    }
  });
};

// 导出方法中新增stream
export { get, post, put, del, stream };